"use strict";
const Service = require("egg").Service;
const { httpCode } = require("../../utils/userConfig");
const SystemErrException = require("../../exception/systemError");
const LogicErrException = require("../../exception/logicError");
const await = require("await-stream-ready/lib/await");
const { Op } = require("sequelize");
const { v4: uuidv4 } = require('uuid');

class UnitMgmtService extends Service {

  async add(unit) {
    try {
      const { ctx } = this;
      await ctx.model.Organization.Units.create(unit);
      return {
        code: httpCode.SUCCESS,
        message: "新增单位成功"
      }
    } catch (error) {
      throw new SystemErrException("单位添加异常：" + error);
    }
  }

  async list(requestData) {
    const { ctx } = this;
    let { currentPage = 1, pageSize = 999 } = requestData;
    let { count, rows } = await ctx.model.Organization.Units.findAndCountAll({
      offset: (Number(currentPage) - 1) * Number(pageSize),
      limit: Number(pageSize),
      order: [['create_date', 'desc']],
    });
    return {
      data: {
        data: rows,
        count
      },
      code: httpCode.SUCCESS,
      message: '单位列表查询成功！'
    }
  }

  async update(unit) {
    const { id, name, remark } = unit;
    await this.ctx.model.Organization.Units.update(
      {
        name, remark
      },
      {
        where: { id },
      }
    );
    return {
      code: httpCode.SUCCESS,
      message: "单位信息更新成功！",
    };
  }

  async delete({ id }) {
    const { ctx } = this;
    await ctx.model.Organization.Units.destroy({
      where: { id }
    });
    return {
      code: httpCode.SUCCESS,
      message: "单位信息删除成功！"
    }
  }

}

module.exports = UnitMgmtService;
